﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ExpressionEngine
{
    /// <summary>
    /// 函数类，标示引擎内置函数：Tan(),ATan(),Cos()等，也可以是用户自定义函数
    /// </summary>
    public class Function : OperationSymbol
    {
        /// <summary>
        /// 函数实现类
        /// </summary>
        private string _clazz;
        public string Clazz
        {
            get { return _clazz; }
            set { _clazz = value; }
        }

        /// <summary>
        /// 是否是静态函数
        /// </summary>
        private bool _bStatic;
        public bool BStatic
        {
            get { return _bStatic; }
            set { _bStatic = value; }
        }

        /// <summary>
        /// 函数计算(反射实现)
        /// </summary>
        /// <returns></returns>
        public override Variable operate()
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            object obj = assembly.CreateInstance(this._clazz);
            if (obj == null)
                throw new Exception("找不到创建的函数所在类型");

            Type type = obj.GetType();
            MethodInfo method = type.GetMethod(this.Identifier);

            if (method == null)
                throw new Exception("类中找不到Function对应的函数");

            object[] parameters = base.Operands.ToArray<object>(); 
            object varResult = null;
            if (_bStatic)
                varResult = method.Invoke(null, parameters);
            else
                varResult = method.Invoke(obj, parameters);

            return ToVariable(varResult);
        }

        private Variable ToVariable(object varResult)
        {
            Variable var = varResult as Variable;
            if (var == null)
                throw new Exception("类型出现错误");

            return var;
        }
    }
}
